Canvas Widget Example


In [ ]:
ll ../widget_canvas/

In [2]:
fname = '../widget_canvas/widget_canvas.js'

f = os.path.abspath(fname)
js = IPython.display.Javascript(filename=f)  # data=None, url=None, filename=None, lib=None

print('inject!')
IPython.display.display(js)


inject!

In [1]:
from __future__ import print_function, unicode_literals, division, absolute_import

import IPython

from widget_canvas import CanvasImage


inject!

Load some image data

Load test data using my own image file reader helper function based on PIL/Pillow.


In [12]:
from widget_canvas.image import read

data_image = read('images/Whippet.jpg')

data_image.shape


Out[12]:
(220, 320, 3)

My New Canvas Widget

My new canvas widget is simpler to use than IPython's built-in image display widget since it takes a Numpy array as input. Behind the scenes it takes care of compressing and encoding the data and then feeding it into the canvas element in a manner similar to the example just above.


In [13]:
wid_canvas = CanvasImage(data_image)

wid_canvas.border_color = 'black'
wid_canvas.border_width = 2

wid_canvas

Changing the displayed image is as easy as setting the data property to a new Numpy array.


In [ ]:
data_image_2 = read('images/Doberman.jpg')

wid_canvas.data = data_image_2

Mouse events


In [ ]:
# Build an event handler function.
def simple_handler(wid, info):
    msg = 'Click: {:3d}, {:3d}'.format(info['canvasX'], info['canvasY'])
    print(msg)

# Attach the handler to widget's `on_click` events.
wid_canvas.on_mouse_click(simple_handler)

Try it out!

Click on the image above and see your mouse X,Y information displayed.


In [ ]: